package com.saxon.system.security.config;


import com.saxon.system.ajax.AjaxAuthFailHandler;
import com.saxon.system.ajax.AjaxAuthSuccessHandler;
import com.saxon.system.filter.JWTTokenFilter;
import com.saxon.system.filter.JwtFilter;
import com.saxon.system.service.impl.SysAuthUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity配置
 *
 * @author saxon
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    SysAuthUserServiceImpl sysAuthUserService;

    @Autowired
    AjaxAuthFailHandler ajaxAuthFailHandler;

    @Autowired
    AjaxAuthSuccessHandler ajaxAuthSuccessHandler;

    /**
     * 授权
     */
    @Override
    protected void configure (HttpSecurity http) throws Exception {
        http.authorizeRequests ()
                .antMatchers ("/auth/login", "/auth/code", "/auth/info", "/auth/test")
                .hasAnyAuthority ("admin")
                .and ()
                .addFilterBefore (new JWTTokenFilter ("", authenticationManager ()), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore (new JwtFilter (), UsernamePasswordAuthenticationFilter.class)
                .csrf ().disable ();
    }


    @Override
    protected void configure (AuthenticationManagerBuilder auth) {
        try {
            auth.userDetailsService (sysAuthUserService).passwordEncoder (new BCryptPasswordEncoder ());
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}
